
package com.ahhwxx.lib;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.ahhwxx.lib.view.ARecognize;
import com.ym.android.engine.pn.OcrEngine;
import com.ym.android.other.pn.CameraManager;
import com.ym.android.vo.Plate;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * 相机拍照类
 */
public class ACamera extends AppCompatActivity implements SurfaceHolder.Callback {

    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private ImageButton mShutter;
    private ImageButton mFlash_true;

    private CameraManager mCameraManager;
    private String flashModel = Parameters.FLASH_MODE_OFF;

    private ArrayList<String> imagesName = new ArrayList<String>();
    private byte[] plateData = null;
    public static final int REQUEST_CODE_RECOG = 113;            //	识别
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                imagesName.add((String) msg.obj);
                plateData = msg.getData().getByteArray("picData");
//				Intent aRecognize = new Intent(getApplicationContext(), ARecognize.class);
//				aRecognize.putExtra("imagesName", imagesName);
//				aRecognize.putExtra("plateData", plateData);
//				startActivityForResult(aRecognize, REQUEST_CODE_RECOG);


                OcrEngine ocrEngine = new OcrEngine();
                Plate plate = new Plate();
                String imagePath = "sdcard/palte.jpg";
                Intent data2 = new Intent();
                plate = ocrEngine.recognize(ACamera.this, msg.getData().getByteArray("picData"), imagePath);
                if (plate.getRecogStatus() == OcrEngine.RECOG_OK) {
                    try {
                        String result = new String(plate.getCharInfo(), "GBK");
                        String json = result.substring(0, result.lastIndexOf("}") + 1);
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            IdentifyInfo info = new IdentifyInfo();
                            info.setColor(jsonObject.getString("Color"));
                            info.setLayer(jsonObject.getString("Layer"));
                            info.setNum(jsonObject.getString("Num"));
                            data2.putExtra("IdentifyInfo", info);
                            setResult(200, data2);
                        } catch (JSONException e) {
                            setResult(-100);
                            e.printStackTrace();
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    setResult(-100);
                }
                finish();
            } else {
                Toast.makeText(getApplicationContext(), "拍照失败", Toast.LENGTH_SHORT).show();
                mCameraManager.initDisplay();
                mShutter.setEnabled(true);
            }
        }

    };

    private ActivityResultLauncher<String> launcher = registerForActivityResult(new ActivityResultContracts.RequestPermission(),
            result -> {
                if (result.equals(true)) {
                    //权限获取到之后的动作
//                    init();
                    setContentView(R.layout.bcr_camera);
                    mCameraManager = new CameraManager(this, mHandler);
                    initViews();
                } else {
                    Toast.makeText(this,"没有获得相机权限，请从设置中授权！",Toast.LENGTH_SHORT).show();
                    finish();
                }
            });

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        launcher.launch(Manifest.permission.CAMERA);
    }

    @Override
    protected void onResume() {
        imagesName.clear();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        safeRelease();
        super.onDestroy();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mShutter.setEnabled(true);
        mCameraManager.initDisplay();
    }

    private void initViews() {
        // find view
        mShutter = (ImageButton) findViewById(R.id.camera_shutter);
        mFlash_true = (ImageButton) findViewById(R.id.camera_flash_1);
//        findViewById(R.id.bt_cancel).setOnClickListener(view -> {finish();});

        // set view
        mShutter.setOnClickListener(mLsnClick);
        mFlash_true.setOnClickListener(mLsnClick);

        mSurfaceView = (SurfaceView) findViewById(R.id.camera_preview);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    private OnClickListener mLsnClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.camera_shutter) {
                mShutter.setEnabled(false);
                mCameraManager.requestFocuse();
            } else if (id == R.id.camera_flash_1) {
                setFlashModel();
            }
        }

    };

    private void setFlashModel() {
        Log.d("test", "-------->>" + flashModel);
        if (Parameters.FLASH_MODE_ON.equals(flashModel)) {
            if (mCameraManager.isSupportFlash(Parameters.FLASH_MODE_OFF)) {
                flashModel = Parameters.FLASH_MODE_OFF;
                mFlash_true.setImageResource(R.drawable.ic_flash_off_24);
            } else if (mCameraManager.isSupportFlash(Parameters.FLASH_MODE_AUTO)) {
                flashModel = Parameters.FLASH_MODE_AUTO;
                mFlash_true.setImageResource(R.drawable.ic_flash_auto_24);
            }

        } else if (Parameters.FLASH_MODE_OFF.equals(flashModel)) {
            if (mCameraManager.isSupportFlash(Parameters.FLASH_MODE_AUTO)) {
                flashModel = Parameters.FLASH_MODE_AUTO;
                mFlash_true.setImageResource(R.drawable.ic_flash_auto_24);
            } else if (mCameraManager.isSupportFlash(Parameters.FLASH_MODE_ON)) {
                flashModel = Parameters.FLASH_MODE_ON;
                mFlash_true.setImageResource(R.drawable.ic_flash_on_24);
            } else {

            }
        } else if (Parameters.FLASH_MODE_AUTO.equals(flashModel)) {
            if (mCameraManager.isSupportFlash(Parameters.FLASH_MODE_ON)) {
                flashModel = Parameters.FLASH_MODE_ON;
                mFlash_true.setImageResource(R.drawable.ic_flash_on_24);
            } else if (mCameraManager.isSupportFlash(Parameters.FLASH_MODE_OFF)) {
                flashModel = Parameters.FLASH_MODE_OFF;
                mFlash_true.setImageResource(R.drawable.ic_flash_off_24);
            } else {
            }
        } else {

        }
        try {
            mCameraManager.setCameraFlashMode(flashModel);
        } catch (Exception e) {
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // Debug.i(TAG, "surfaceCreated");
        try {
            mCameraManager.openCamera(holder);
            if (flashModel == null || !mCameraManager.isSupportFlash(flashModel)) {
                flashModel = mCameraManager.getDefaultFlashMode();
            }
            mCameraManager.setCameraFlashMode(flashModel);
        } catch (RuntimeException e) {
//            Toast.makeText(this, "相机未正常开启，请重启手机后重试！", Toast.LENGTH_SHORT).show();
            launcher.launch(Manifest.permission.CAMERA);
        } catch (IOException e) {
            Toast.makeText(this, "相机未正常开启，请重启手机后重试！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (width > height) {
            mCameraManager.setPreviewSize(width, height);
        } else {
            mCameraManager.setPreviewSize(height, width);
        }
        mCameraManager.initDisplay();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCameraManager.closeCamera();
    }

    private void safeRelease() {
        if (imagesName != null) {
            imagesName.clear();
            imagesName = null;
        }
    }

}